package com.sn.miaosha.backdoor.util;

import com.ncarzone.framework.insight.common.utils.JsonUtils;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * json工具类
 * 先直接用架构组的，有个性化需求在改
 *
 * @author mazhenjie
 * @since 2020/6/1
 */
public class JsonUtil {

    public static String toJSONString(Object obj) {
        return JsonUtils.toJSONString(obj);
    }

    public static <T> T parseObject(String jsonStr, Class<T> objClass) {
        return JsonUtils.parseObject(jsonStr, objClass);
    }

    public static <T> T parseObject(byte[] bytes, Class<T> objClass) {
        return JsonUtils.parseObject(new String(bytes, StandardCharsets.UTF_8), objClass);
    }

    public static <T> T parseObject(String jsonStr, Type typeOfT) {
        return JsonUtils.parseObject(jsonStr, typeOfT);
    }

    public static String jsonPretty(String compressedJson) {
        return JsonUtils.jsonPretty(compressedJson);
    }

    public static <T> List<T> toObjectList(String jsonStr, Class<T> clazz) {
        Type type = new ParameterizedTypeImpl(clazz);
        return JsonUtils.parseObject(jsonStr, type);
    }

    /**
     * 反射用内部类
     */
    private static class ParameterizedTypeImpl implements ParameterizedType {

       private Class clazz;

        public ParameterizedTypeImpl(Class clz) {
            clazz = clz;
        }

        @Override
        public Type[] getActualTypeArguments() {
            return new Type[]{clazz};
        }

        @Override
        public Type getRawType() {
            return List.class;
        }

        @Override
        public Type getOwnerType() {
            return null;
        }
    }
}
